package com.xjd.edu.toolkit.helper;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * Web 编解码（Base64）工具
 *
 * @author wangyu
 * @since 2022/4/12
 */
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class WebEncodeHelper {

    /**
     * 请求是否需要进行编解码
     */
    public static final String HEADER_CHECK_NAME = "User-Check";
    /**
     * 响应是否已经编码
     */
    public static final String HEADER_ENCODE_NAME = "XBodyEncode";
    /**
     * 请求是否已经解码
     */
    public static final String HEADER_DECODE_NAME = "XBodyDecode";

    /**
     * 检查请求是否需要进行编解码
     *
     * @param request
     * @return
     */
    public static boolean checkRequest(HttpServletRequest request) {
        final String value = request.getHeader(HEADER_CHECK_NAME);
        return "1.0".equals(value) || "2.0".equals(value);
    }

    /**
     * 检查请求是否已经解码
     *
     * @param request
     * @return
     */
    public static boolean checkRequestDecoded(HttpServletRequest request) {
        return "1".equals(request.getHeader(HEADER_DECODE_NAME));
    }

    /**
     * 标记响应未进行编码
     *
     * @param response
     */
    public static void markResponseNoEncode(HttpServletResponse response) {
        response.setHeader(HEADER_ENCODE_NAME, "0");
    }

    public static String encode(String text) {
        if (text == null) {
            return null;
        }
        return Base64.getEncoder().encodeToString(text.getBytes(StandardCharsets.UTF_8));
    }

    public static String encode(byte[] bytes) {
        if (bytes == null) {
            return null;
        }
        return Base64.getEncoder().encodeToString(bytes);
    }

    public static String decode(String text) {
        if (text == null) {
            return null;
        }
        return new String(Base64.getDecoder().decode(text), StandardCharsets.UTF_8);
    }

    public static String decode(byte[] bytes) {
        if (bytes == null) {
            return null;
        }
        return new String(Base64.getDecoder().decode(bytes), StandardCharsets.UTF_8);
    }

}
